package com.doge.calcalbum.utils

import com.doge.calcalbum.analysis.analysisEvent
import com.doge.calcalbum.analysis.oa_id
import com.doge.calcalbum.analysis.oa_id_error
import com.doge.calcalbum.analysis.oa_id_ok
import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.IGetter

object OAIDUtils {
    private var value: String? = null
    val id: String?
        get() {
            if (value != null) return value
            val cache = disk
            value = cache
            return cache
        }

    fun init() { // OAID/AAID
        log("OAIDUtils require")
        analysisEvent(oa_id)
        DeviceID.getOAID(appContext, object : IGetter {
            override fun onOAIDGetComplete(result: String?) {
                log("OAIDUtils onOAIDGetComplete $result")
                value = result
                saveToDisk(result)
                analysisEvent(oa_id_ok)
            }

            override fun onOAIDGetError(error: Exception?) {
                log("OAIDUtils onOAIDGetError")
                error?.printStackTrace()
                analysisEvent(oa_id_error)
            }
        })
    }

    private val disk: String?
        get() = spReadString("i", "", "oa")

    private fun saveToDisk(value: String?) = runOnIO {
        if (value?.isNotEmpty() == true &&
            value != "00000000-0000-0000-0000-000000000000") {
            spWrite("i", value, "oa")
        }
    }
}